package com.fzu.mmdbproxyframework.cluster.passcloud;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;

import net.sf.json.JSONObject;

public class SendRequest {

	public static String apiServerUrl = "http://192.168.2.100:8080/client/api";

	public static String cookieKey = null;

	private static String sessionKey = null;

	private static long expiretime = 0;

	private static boolean isloggedin = false;

	private static String responseFormat = "json";

	private static String username = "lzq";

	private static String password = "lzq";

	private static String domain = "DBM";

	public static boolean login(String username, String password,
			String domain) {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("response", responseFormat);
		params.put("username", username);
		params.put("password", password);
		params.put("domain", domain);
		String command = "login";
		HttpURLConnection conn = null;
		try {
			StringBuilder sBuilder = new StringBuilder();
			sBuilder.append("command=");
			sBuilder.append(command);
			if (params != null && params.size() > 0) {
				Iterator<String> keys = params.keySet().iterator();
				while (keys.hasNext()) {
					String key = keys.next();
					sBuilder.append("&");
					sBuilder.append(key);
					sBuilder.append("=");
					sBuilder
							.append(URLEncoder.encode(params.get(key), "UTF-8"));
				}
			}

			// Construct request url
			String reqUrl = apiServerUrl + "?" + sBuilder.toString();

			// Send Http GET request
			URL url = new URL(reqUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(3000);

			conn.connect();

			// store cookie
			String headerName = null;
			for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
				if (headerName.equals("Set-Cookie")) {
					String cookie = conn.getHeaderField(i);
					cookie = cookie.substring(0, cookie.indexOf(";"));
					String cookieName = cookie
							.substring(0, cookie.indexOf("="));
					String cookieValue = cookie.substring(
							cookie.indexOf("=") + 1, cookie.length());
					String cookieToSent = cookieName + "=" + cookieValue;
					cookieKey = cookieToSent;
				}
			}

			// Get the response
			StringBuilder result = new StringBuilder();
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			String line;
			try {
				while ((line = rd.readLine()) != null) {
					result.append(line);
				}
			} catch (EOFException ex) {

			} finally {
				rd.close();
			}
			String res = result.toString();
			if (res != null && !res.isEmpty()) {
				JSONObject obj = JSONObject.fromObject(res);
				LoginResponse loginResponse = (LoginResponse) JSONObject
						.toBean(obj.getJSONObject("loginresponse"),
								LoginResponse.class);
				sessionKey = loginResponse.getSessionkey();
				expiretime = System.currentTimeMillis()
						+ Long.parseLong(loginResponse.getTimeout()) * 1000
						- 5000;
				isloggedin = true;
				return true;
			}
			return false;

		} catch (Exception e) {
			return false;
		}
	}

	public static String sendRequest(String command,
			HashMap<String, String> params) {
		HttpURLConnection conn = null;
		if (!isloggedin || System.currentTimeMillis() > expiretime) {
			login(username, password, domain);
		}
		if(null == sessionKey){
			return null;
		}
		if (null == params) {
			params = new HashMap<String, String>();
		}
		params.put("response", responseFormat);
		params.put("sessionkey", sessionKey);
		try {
			// Construct query string
			StringBuilder sBuilder = new StringBuilder();
			sBuilder.append("command=");
			sBuilder.append(command);
			if (params != null && params.size() > 0) {
				Iterator<String> keys = params.keySet().iterator();
				while (keys.hasNext()) {
					String key = keys.next();
					sBuilder.append("&");
					sBuilder.append(key);
					sBuilder.append("=");
					sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8"));
				}
			}
			String reqUrl = apiServerUrl + "?" + sBuilder.toString();
			// Send Http GET request
			URL url = new URL(reqUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(3000);
			if (!command.equals("login")) {
				String cookieToSent = cookieKey;
				// add the cookie to a request
				conn.setRequestProperty("Cookie", cookieToSent);
			}
			conn.connect();
			// Get the response
			StringBuilder result = new StringBuilder();
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			String line;
			try {
				while ((line = rd.readLine()) != null) {
					result.append(line);
				}
			} catch (EOFException ex) {
				System.out.println("EOF exception due to java bug");
			} finally {
				rd.close();
			}
			return result.toString();

		} catch (IOException e) {
			System.out.println(e.getMessage());

		}
		return null;
	}
	public static void main(String[] args) {
//		System.out.println(login(username,password,"tuge"));
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("id", "5c094a34-78f9-4138-80ca-56bbca39a2d9");
		params.put("projectid", "f7ce3688-e6c3-48d4-af2d-9476d7743af0");
		String result = SendRequest.sendRequest(InternetwareCmd.ListAllVMsCmd,params);
		System.out.println(result);
	}
}
